﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CrmCustomizationsExcelAddIn.Data;
using Microsoft.Xrm.Sdk;
using CrmCustomizationsExcelAddIn.Helper;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Xrm.Sdk.Metadata;
using System.Configuration;
using CrmServerConnection;

namespace UnitTest
{
    class RequestGeneratorTestHelper
    {
        public static IOrganizationService connectOrg()
        {
            OrganizationDetailCollection orgResponse;
            CrmConnection connection;
            connection = new CrmConnection(bool.Parse(ConfigurationManager.AppSettings["CRM_SSL"].ToString()), ConfigurationManager.AppSettings["CRM_ADDRESS"].ToString(), ConfigurationManager.AppSettings["CRM_USER"].ToString(), ConfigurationManager.AppSettings["CRM_PASSWORD"].ToString());
            try
            {
                orgResponse = connection.GetDiscoveryService();
                connection.OrganizationName = orgResponse.First().FriendlyName;
                IServiceManagement<IOrganizationService> service = connection.ConnectToOrganization();
                OrganizationServiceProxy organizationProxy = connection.GetOrganizationProxy();
                return organizationProxy;
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            return null;
        }


        public static ExcelMatrix generateRandomExcelMatrix(string rowToTest, int row)
        {
            ExcelMatrix matrix = new ExcelMatrix(ExcelColumsDefinition.MAXNUMBEROFATTRIBUTE, ExcelColumsDefinition.MAXNUMBEROFCOLUMN);
            matrix.AddRow(0, rowToTest.Split('|'));
            return matrix;
        }

        public static void exceuteOperaion(CrmOperationHelper rhelper, IEnumerable<CrmOperation> oplist)
        {
            foreach (var item in oplist)
            {
                rhelper.executeOpertionsCrm(item);
                if (item.operationSucceded == false)
                {
                    Assert.Fail(item.exceptionString);
                }
            }
        }


        public static string getAttributePropertyString(AttributeMetadata attr, int language, OneToManyRelationshipMetadata[] relationship)
        {
            String[] stringArr = new string[ExcelColumsDefinition.MAXNUMBEROFCOLUMN];
            stringArr[ExcelColumsDefinition.HEADERCOL] = string.Format("{0} - ({1})", Utils.getLocalizedLabel(attr.DisplayName.LocalizedLabels, language), attr.SchemaName);
            stringArr[ExcelColumsDefinition.LOGICALNAMEEXCELCOL] = attr.LogicalName;
            stringArr[ExcelColumsDefinition.SCHEMANAMEEXCELCOL] = attr.SchemaName;
            stringArr[ExcelColumsDefinition.DISPLAYNAMEEXCELCOL] = Utils.getLocalizedLabel(attr.DisplayName.LocalizedLabels, language);
            stringArr[ExcelColumsDefinition.DESCRIPTIONEXCELCOL] = Utils.getLocalizedLabel(attr.Description.LocalizedLabels, language);
            stringArr[ExcelColumsDefinition.ATTRIBUTETYPEEXCELCOL] = attr.AttributeType.ToString();
            stringArr[ExcelColumsDefinition.REQUIREDLEVELEXCELCOL] = attr.RequiredLevel.Value.ToString();
            stringArr[ExcelColumsDefinition.ADVANCEDFINF] = attr.IsValidForAdvancedFind.Value.ToString();
            stringArr[ExcelColumsDefinition.SECURED] = attr.IsSecured.Value.ToString();
            stringArr[ExcelColumsDefinition.AUDITENABLED] = attr.IsAuditEnabled.Value.ToString();
            switch (attr.AttributeType)
            {
                case AttributeTypeCode.Integer:
                    stringArr[ExcelColumsDefinition.INTEGERFORMATCOL] = ((IntegerAttributeMetadata)attr).Format != null ? ((IntegerAttributeMetadata)attr).Format.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.INTEGERMAXVALUECOL] = ((IntegerAttributeMetadata)attr).MaxValue != null ? ((IntegerAttributeMetadata)attr).MaxValue.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.INTEGERMINVALUECOL] = ((IntegerAttributeMetadata)attr).MinValue != null ? ((IntegerAttributeMetadata)attr).MinValue.Value.ToString() : string.Empty;
                    break;
                case AttributeTypeCode.Boolean:
                    stringArr[ExcelColumsDefinition.BOOLEANTRUEOPTION] = ((BooleanAttributeMetadata)attr).OptionSet.TrueOption != null ? Utils.getLocalizedLabel(((BooleanAttributeMetadata)attr).OptionSet.TrueOption.Label.LocalizedLabels, language) : string.Empty;
                    stringArr[ExcelColumsDefinition.BOOLEANFALSEOPTION] = ((BooleanAttributeMetadata)attr).OptionSet.FalseOption != null ? Utils.getLocalizedLabel(((BooleanAttributeMetadata)attr).OptionSet.FalseOption.Label.LocalizedLabels, language) : string.Empty;
                    stringArr[ExcelColumsDefinition.BOOLEANDEFAULTVALUE] = ((BooleanAttributeMetadata)attr).DefaultValue != null ? "'" + ((BooleanAttributeMetadata)attr).DefaultValue.Value.ToString() : string.Empty;
                    break;
                case AttributeTypeCode.DateTime:
                    stringArr[ExcelColumsDefinition.DATETIMEFORMATCOL] = ((DateTimeAttributeMetadata)attr).Format != null ? ((DateTimeAttributeMetadata)attr).Format.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.DATETIMEIMEMODECOL] = ((DateTimeAttributeMetadata)attr).ImeMode != null ? ((DateTimeAttributeMetadata)attr).ImeMode.Value.ToString() : string.Empty;
                    break;
                case AttributeTypeCode.String:
                    stringArr[ExcelColumsDefinition.STRINGMAXLENGTHCOL] = ((StringAttributeMetadata)attr).MaxLength != null ? ((StringAttributeMetadata)attr).MaxLength.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.STRINGFORMATCOL] = ((StringAttributeMetadata)attr).Format != null ? ((StringAttributeMetadata)attr).Format.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.STRINGIMEMODECOL] = ((StringAttributeMetadata)attr).ImeMode != null ? ((StringAttributeMetadata)attr).ImeMode.Value.ToString() : string.Empty;
                    break;
                case AttributeTypeCode.Picklist:
                    PicklistAttributeMetadata pkListMetadata = (PicklistAttributeMetadata)attr;
                    //if (pkListMetadata.OptionSet != null)
                    //{
                    //    ((PicklistAttributeMetadata)attr).OptionSet.MetadataId.ToString();
                    //    addOptionSetHyperlink(row.Worksheet, stringArr[ExcelColumsDefinition.PICKLISTREF ], pkListMetadata.OptionSet.MetadataId.ToString(), pkListMetadata.OptionSet.Options);
                    //    stringArr[ExcelColumsDefinition.PICKLISTGLOBAL ] = "'" + pkListMetadata.OptionSet.IsGlobal;
                    //    stringArr[ExcelColumsDefinition.PICKLISTDEFAULTVALUE ] = pkListMetadata.DefaultFormValue != null ? pkListMetadata.DefaultFormValue.Value.ToString() : string.Empty;
                    //    stringArr[ExcelColumsDefinition.PICKLISTGLOBALNAME ] = pkListMetadata.OptionSet.Name;
                    //}
                    break;
                case AttributeTypeCode.Memo:
                    stringArr[ExcelColumsDefinition.MEMOFORMATCOL] = ((MemoAttributeMetadata)attr).Format != null ? ((MemoAttributeMetadata)attr).Format.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.MEMOIMEMODECOL] = ((MemoAttributeMetadata)attr).ImeMode != null ? ((MemoAttributeMetadata)attr).ImeMode.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.MEMOMAXLENGTHCOL] = ((MemoAttributeMetadata)attr).MaxLength != null ? ((MemoAttributeMetadata)attr).MaxLength.Value.ToString() : string.Empty;
                    break;
                case AttributeTypeCode.Double:
                    stringArr[ExcelColumsDefinition.DOUBLEMAXVALUE] = ((DoubleAttributeMetadata)attr).MaxValue != null ? ((DoubleAttributeMetadata)attr).MaxValue.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.DOUBLEMINVALUE] = ((DoubleAttributeMetadata)attr).MinValue != null ? ((DoubleAttributeMetadata)attr).MinValue.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.DOUBLEPRECISION] = ((DoubleAttributeMetadata)attr).Precision != null ? ((DoubleAttributeMetadata)attr).Precision.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.DOUBLEIMEMODE] = ((DoubleAttributeMetadata)attr).ImeMode != null ? ((DoubleAttributeMetadata)attr).ImeMode.Value.ToString() : string.Empty;
                    break;
                case AttributeTypeCode.Decimal:
                    stringArr[ExcelColumsDefinition.DECIMALMAXVALUE] = ((DecimalAttributeMetadata)attr).MaxValue != null ? ((DecimalAttributeMetadata)attr).MaxValue.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.DECIMALMINVALUE] = ((DecimalAttributeMetadata)attr).MinValue != null ? ((DecimalAttributeMetadata)attr).MinValue.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.DECIMALPRECISION] = ((DecimalAttributeMetadata)attr).Precision != null ? ((DecimalAttributeMetadata)attr).Precision.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.DECIMALIMEMODE] = ((DecimalAttributeMetadata)attr).ImeMode != null ? ((DecimalAttributeMetadata)attr).ImeMode.Value.ToString() : string.Empty;
                    break;
                case AttributeTypeCode.Money:
                    stringArr[ExcelColumsDefinition.MONEYPRECISION] = ((MoneyAttributeMetadata)attr).Precision != null ? ((MoneyAttributeMetadata)attr).Precision.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.MONEYMAXVALUE] = ((MoneyAttributeMetadata)attr).MaxValue != null ? ((MoneyAttributeMetadata)attr).MaxValue.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.MONEYMINVALUE] = ((MoneyAttributeMetadata)attr).MinValue != null ? ((MoneyAttributeMetadata)attr).MinValue.Value.ToString() : string.Empty;
                    stringArr[ExcelColumsDefinition.MONEYIMEMODE] = ((MoneyAttributeMetadata)attr).ImeMode != null ? ((MoneyAttributeMetadata)attr).ImeMode.ToString() : string.Empty;
                    break;
                case AttributeTypeCode.Lookup:
                    stringArr[ExcelColumsDefinition.LOOKUPRELATIONSHIPNAME] = getRealationShipName(attr.LogicalName, relationship);
                    stringArr[ExcelColumsDefinition.LOOKUPTARGET] = ((LookupAttributeMetadata)attr).Targets != null && ((LookupAttributeMetadata)attr).Targets.Count() > 0 ? ((LookupAttributeMetadata)attr).Targets[0] : string.Empty;
                    break;
            }


            return string.Join("|", stringArr);
        }

        public static string getRealationShipName(string attributeName, OneToManyRelationshipMetadata[] relationship)
        {
            IEnumerable<OneToManyRelationshipMetadata> attributeRelationship = relationship.Where(x => x.ReferencingAttribute == attributeName);
            if (attributeRelationship.Count() > 0)
            {
                return attributeRelationship.First().SchemaName;
            }
            return string.Empty;
        }

    }
}
